﻿using GalaSoft.MvvmLight.Messaging;
using KINLO.DRV.Drv;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks; 

namespace KINLO.DRV.Machine
{

    public class ElecBalanceMachine
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ElecBalanceMachine));
        #region 字段 
        public ElectronicBalanceSocketDrv ElecBalance;
        System.Timers.Timer timer;
        public string ID { get; set; }
        public bool IsWeightFin { get; set; }
        public Decimal Weight { get; set; }
        public string Unit { get; set; } = "";
        public string Symbol { get; set; }
        public int startIndex { get; set; }
        public Decimal CurrWeight { get; set; }
        public bool IsRunning { get; set; }
        public Task RunTask { get; set; }
        public string IP { get; set; }
        public int Port { get; set; }
        int sleepTime = 100;
        int timeoutCount = 0;
        FileStream file;
        #endregion

        #region 方法
        public ElecBalanceMachine(string ip, int port, string id, double interval = 300, int dataLen = 20,int startIndex = 0)
        {
            Random rnd = new Random(DateTime.Now.Millisecond);
            IP = ip;
            Port = port;
            ID = id;
            this.startIndex = startIndex;
            //file = File.OpenWrite(this.startIndex+"_"+ rnd.Next(9999999) + ".txt");
            ElecBalance = new ElectronicBalanceSocketDrv(ip, port); 
            Task.Run(() => {
                RunTask = Run();
            });
        }
        public ElecBalanceMachine(string ipaddr, string id, double interval = 300, int dataLen = 20)
        {

            var addr = ipaddr.Split(':');
            IP = addr[0];
            Port = int.Parse(addr[1]); 
            ID = id;
            ElecBalance = new ElectronicBalanceSocketDrv(IP, Port); 
            Task.Run(() => {
                RunTask = Run();
            });
        } 

        Object locker1 = new object();         
        public Task Run()
        {
            Log(string.Format("创建电子称:{0}{1} ", ElecBalance.IpAddr, ElecBalance.Port));
            return Task.Factory.StartNew(() => {
                try
                {
                    while (true)
                    {
                        HandleMessage(Read());
                        Thread.Sleep(sleepTime);
                    }
                }
                catch (Exception ex)
                {
                    Log(string.Format("电子称:{0} {1} 发生异常 {2} ", ElecBalance.IpAddr, ElecBalance.Port, ex.Message));
                }
            },TaskCreationOptions.LongRunning);

        }

        public bool IsLoop = true;

        void HandleMessage(byte[] msg)
        {
            try
            {
                if (msg != null && msg.Length >= 20)
                {
                    sleepTime = 100;
                    timeoutCount = 0;
                    var sect = Encoding.Default.GetString(msg); 
                    var section1 = Encoding.Default.GetString(msg, 0, 2);//ST 
                    var section2 = Encoding.Default.GetString(msg, 3, 2);//GS 
                    var section3 = Encoding.Default.GetString(msg, 6, 1);//+
                    var section4 = Encoding.Default.GetString(msg, 7, 7);//value
                    var section5 = Encoding.Default.GetString(msg, 15, 2); //\r\n 
                    decimal w = default(decimal);
                   if(! decimal.TryParse(section4, out w))
                    {
                       // ElecBalance.BlnConnected = false;
                    }
                    //if (!decimal.TryParse(section4, out w))//如果无法解析value为float
                    //{
                    //    w = (decimal)9889898.25235;
                    //}
                    this.CurrWeight = w;
                    Unit = section3??"";
                    if (section1.ToUpper() == "ST" && (w > 10) && !section3.Contains("-"))
                    {
                        this.Weight = w;
                        this.IsWeightFin = true;
                        Unit = section3??"";
                    } 
                }
                else
                {
                    timeoutCount++;
                    if (timeoutCount == 50)
                    {
                        sleepTime = 1000;
                    }
                    else if (timeoutCount > 100)
                    {
                        sleepTime = 3000;
                    }
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("HandleMessage {0}", ex));
            }
        }
        public bool IsConnected
        {
            get { return ElecBalance.BlnConnected; }
        }
        public byte[] Read()
        {
            return ElecBalance.Read();
        }
        public void ServiceControl(bool act)
        {
            if (act == false)
            {
                ElecBalance.Close();
            }
            if (act == true && ElecBalance.BlnConnected != true)
            {
                ElecBalance.Open();
                if (RunTask.IsCanceled || RunTask.IsCompleted || RunTask.IsFaulted)
                {
                    RunTask = Run();
                }
            }
            //timer.Enabled = act;
        }
        public void ClearZero()
        {
            ElecBalance.ClearZero();
        }


        public void Log(string msg)
        {
            log.Info(msg);
            Messenger.Default.Send(msg, "ReceiveEventInfo");
        }
        #endregion
    }

}
